// pages/using/using.js
var QQMapWX = require("../../lib/qqmap-wx-jssdk.js")
var qqmapsdk;
import drawQrcode from '../../lib/weapp.qrcode.esm.js';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showQRCode: false,
    qrcodeImagePath: '',
    qrcodeWidth: 0,
    sliderPosition: 0,
    showMap: false,
    //位置名称
    now_address_name: '',
    //位置名称对应的详细地址
    now_address: '',
    text: '输入您的目的地',
    speed: 0,
    battery: 0,
    user_info: {},
    using_car_info: {},
    order_info: {},
    end_position: '',
    need_save_lat: 0,
    need_save_lng: 0,
    distance: 0,
    duration_time: 0,
    taxi_fare: 0,
    need_save_address: '',
    petrol__emissions: 0,
    electronic_emissions: 0,
    save_carbon_emissions: 0,
    tree__emissions: 0,
    gradientColor: {
      '0%': 'red',
      '100%': 'blue',
    },
  },

  touchEnd(e) {
    const sliderPosition = e.changedTouches[0].clientX - 50;
    const unlockPosition = 250; // 自定义解锁位置

    console.log("滑动结束，当前位置:", sliderPosition);

    if (sliderPosition >= unlockPosition) {
      console.log("解锁成功");
      this.setData({
        sliderPosition: 0
      });
      // 在这里执行您需要的操作，例如跳转到其他页面
      this.overUseCar(e);
    } else {
      console.log("解锁失败");
      // 将滑块重置到初始位置
      this.setData({
        sliderPosition: 0
      });
    }
  },
  touchStart(e) {
    this.startX = e.touches[0].clientX;
    this.startSliderPosition = this.data.sliderPosition;
  },
  touchMove(e) {
    const moveX = e.touches[0].clientX - this.startX;
    const newSliderPosition = Math.min(Math.max(0, this.startSliderPosition + moveX), 250); // 根据滑动范围限制滑块位置
    this.setData({
      sliderPosition: newSliderPosition
    });
  },

  onChange(event) {
    console.log(event.detail)
    this.setData({
      activeNames: event.detail,
    });
  },

  handlePreviewImage(e) {
    wx.previewImage({
      current: 'http://localhost:80/common/download?name=' + this.data.using_car_info.image, // 当前显示图片的http链接
      urls: ['http://localhost:80/common/download?name=' + this.data.using_car_info.image] // 需要预览的图片http链接列表
    })
  },
  showQRCode(e) {
    const that = this;
    const text = this.data.using_car_info.carNumber + "," + this.data.using_car_info.id;
    if (this.data.qrcodeImagePath === '') {
      this.setData({
        showQRCode: true
      })
      drawQrcode({
        type: 'canvas',
        width: 200, // 必须，二维码宽度，与canvas的width保持一致
        height: 200, // 必须，二维码高度，与canvas的height保持一致
        background: '#ffffff', //	非必须，二维码背景颜色，默认值白色
        foreground: '#2bb15e', // 非必须，二维码前景色，默认值黑色 	'#000000'
        canvasId: 'myQrcode',
        text: text,
        image: {
          // imageResource: '../../images/icon.png', // 指定二维码小图标
          dx: 70,
          dy: 70,
          dWidth: 60,
          dHeight: 60
        }
      });
      // 等待生成二维码
      setTimeout(() => {
        wx.canvasToTempFilePath({
          canvasId: 'myQrcode',
          success: (result) => {
            console.log(result.tempFilePath);
            that.setData({
              qrcodeImagePath: result.tempFilePath,
              showQRCode: false
            });
            wx.previewImage({
              urls: [this.data.qrcodeImagePath] // 需要预览的图片http链接列表
            })
          },
          fail: (err) => {
            console.error('保存二维码到本地失败:', err);
          }
        });
      }, 1000);
    } else {
      wx.previewImage({
        urls: [this.data.qrcodeImagePath] // 需要预览的图片http链接列表
      })
    }
  },

  drawSpeedometer: function (speed, canvasWidth, canvasHeight) {
    const ctx = wx.createCanvasContext('speedometer');
    // 清除canvas上的内容
    ctx.clearRect(0, 0, canvasWidth, canvasHeight);
    const centerX = canvasWidth / 2;
    const centerY = canvasHeight / 2;
    const radius = Math.min(canvasWidth, canvasHeight) * 0.4;

    // 绘制仪表盘背景
    ctx.beginPath();
    ctx.arc(centerX, centerY, radius, 0.65 * Math.PI, 2.35 * Math.PI);
    ctx.lineWidth = radius * 0.2;
    ctx.strokeStyle = '#ccc';
    ctx.stroke();


    // 绘制刻度线和刻度值
    const totalTicks = 20; // 更改刻度数量
    const maxSpeed = 200; // 更改最大速度
    for (let i = 0; i <= totalTicks; i++) {
      const tickAngle = 0.65 * Math.PI + i * (1.7 * Math.PI / totalTicks); // 更改角度范围
      const tickLength = i % 2 === 0 ? 15 : 7;
      const innerX = centerX + (radius - tickLength) * Math.cos(tickAngle);
      const innerY = centerY + (radius - tickLength) * Math.sin(tickAngle);
      const outerX = centerX + radius * Math.cos(tickAngle);
      const outerY = centerY + radius * Math.sin(tickAngle);

      ctx.beginPath();
      ctx.moveTo(innerX, innerY);
      ctx.lineTo(outerX, outerY);
      ctx.lineWidth = i % 2 === 0 ? 3 : 1;
      ctx.strokeStyle = '#333';
      ctx.stroke();

      // 绘制刻度值
      if (i % 2 === 0) {
        const tickValue = i * (maxSpeed / totalTicks);
        const textX = centerX + (radius - 30) * Math.cos(tickAngle) - 6;
        const textY = centerY + (radius - 30) * Math.sin(tickAngle) + 4;
        ctx.setFontSize(12);
        ctx.fillStyle = 'black';
        ctx.fillText(tickValue, textX, textY);
      }
    }

    // 计算速度指针角度
    const angle = 0.65 * Math.PI + (speed / maxSpeed) * (1.7 * Math.PI);

    // 绘制速度指针
    ctx.beginPath();
    ctx.moveTo(centerX, centerY);
    ctx.lineTo(centerX + radius * Math.cos(angle), centerY + radius * Math.sin(angle));
    ctx.lineWidth = 3;
    ctx.strokeStyle = '#4CAF50';
    ctx.stroke();

    // 绘制仪表盘中心
    ctx.beginPath();
    ctx.arc(centerX, centerY, 5, 0, 2 * Math.PI);
    ctx.fillStyle = '#4CAF50';
    ctx.fill();

    // 绘制速度文本
    ctx.setFontSize(11);
    ctx.fillStyle = 'black';
    ctx.fillText(speed + ' km/h', centerX - 20, centerY + 20);

    ctx.draw();
  },

  formSubmit() {
    var that = this;
    that.setData({
      showMap: true
    })
    var _this = that;
    qqmapsdk.geocoder({
      //获取表单传入地址
      address: that.data.need_save_address, //地址参数，例：固定地址，address: '北京市海淀区彩和坊路海淀西大街74号'
      success: function (res) { //成功后的回调
        console.log(res);
        console.log("输入的地址转化过来是:", res.result.location)
        var latitude = res.result.location.lat;
        var longitude = res.result.location.lng;
        _this.setData({
          end_position: latitude + "," + longitude,
          need_save_lat: latitude,
          need_save_lng: longitude
        })
        var res = res.result;
        //根据地址解析在地图上标记解析地址位置
        _this.setData({ // 获取返回结果，放到markers及poi中，并在地图展示
          markers: [{
            id: 0,
            title: res.title,
            latitude: latitude,
            longitude: longitude,
            iconPath: '../../pages/images/position.png', //图标路径
            width: 20,
            height: 20,
            callout: { //可根据需求是否展示经纬度
              content: that.data.need_save_address,
              color: '#000',
              display: 'ALWAYS'
            }
          }],
          poi: { //根据自己data数据设置相应的地图中心坐标变量名称
            latitude: latitude,
            longitude: longitude
          }
        });
        //调用距离计算接口
        qqmapsdk.direction({
          mode: 'driving',
          //from参数不填默认当前地址
          //from: _this.data.start,
          to: _this.data.end_position,
          success: function (res) {
            console.log("成功，返回的结果是：" + res.result.routes[0]);
            var ret = res;
            var coors = ret.result.routes[0].polyline,
              pl = [];
            _this.setData({
              distance: ret.result.routes[0].distance.toFixed(2),
              duration_time: ret.result.routes[0].duration,
              taxi_fare: ret.result.routes[0].taxi_fare.fare,
              petrol__emissions: (0.157 * (ret.result.routes[0].distance / 1000)).toFixed(2),
              electronic_emissions: (0.113 * (ret.result.routes[0].distance / 1000)).toFixed(2),
              save_carbon_emissions: (0.157 * (ret.result.routes[0].distance / 1000) - 0.113 * (ret.result.routes[0].distance / 1000)).toFixed(2),
              tree__emissions: ((0.157 * (ret.result.routes[0].distance / 1000) - 0.113 * (ret.result.routes[0].distance / 1000)) / 8).toFixed(2)
            })
            //坐标解压（返回的点串坐标，通过前向差分进行压缩）
            var kr = 1000000;
            for (var i = 2; i < coors.length; i++) {
              coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
            }
            //将解压后的坐标放入点串数组pl中
            for (var i = 0; i < coors.length; i += 2) {
              pl.push({
                latitude: coors[i],
                longitude: coors[i + 1]
              })
            }
            console.log(pl)
            //设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
            _this.setData({
              latitude: pl[0].latitude,
              longitude: pl[0].longitude,
              polyline: [{
                points: pl,
                color: '#33FF66',
                arrowLine: true,
                borderColor: 'Black',
                width: 4
              }]
            })
          },
          fail: function (error) {
            console.error(error);
          },
          complete: function (res) {
            console.log(res);
          }
        });
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
        console.log(res);
      }
    })

  },

  startPlanRoute(e) {
    var that = this;
    wx.chooseLocation({
      success(res) {
        console.log("位置名称：" + res.name)
        console.log("详细地址:" + res.address)
        that.setData({
          text: res.address,
          need_save_address: res.address
        })
        that.formSubmit();
      }
    })
  },
  overPlanRoute(e) {
    this.setData({
      showMap: false
    })
  },

  makePhoneCallPolice(e) {
    wx.makePhoneCall({
      phoneNumber: '110', // 例如: '110'
      success: () => {
        console.log('拨打电话成功！');
      },
      fail: (err) => {
        console.error('拨打电话失败：', err);
      }
    });
  },

  makePhoneCallCustomerService(e) {
    wx.makePhoneCall({
      phoneNumber: '17665472607', // 例如: '110'
      success: () => {
        console.log('拨打电话成功！');
      },
      fail: (err) => {
        console.error('拨打电话失败：', err);
      }
    });
  },

  toMyFriendsToHelp(e) {
    const latitude = this.data.latitude;
    const longitude = this.data.longitude;
    console.log("当前位置：" + longitude + "," + latitude)
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage']
    });
    this.onShareAppMessage = function () {
      return {
        title: '紧急求助!',
        desc: '我遇到了紧急情况，需要你的帮助！我目前所在地址是:' + this.data.now_address,
        path: `/pages/sharelocation/sharelocation?latitude=${latitude}&longitude=${longitude}`
      };
    };
    wx.showModal({
      title: '紧急求助',
      content: '已经将位置信息保存，请点击右上角的分享按钮，将您的位置信息分享给紧急联系人。',
      showCancel: false
    });
  },

  toFeedBack(e) {
    wx.navigateTo({
      url: '/pages/feedback/feedback',
    })
  },

  //结束使用车辆时，页面跳转前进行数据的清空，因为使用的switchTab来进行的跳转，数据需要手动清空
  clearData() {
    this.setData({
      showQRCode: false,
      qrcodeImagePath: '',
      qrcodeWidth: 0,
      sliderPosition: 0,
      showMap: false,
      //位置名称
      now_address_name: '',
      //位置名称对应的详细地址
      now_address: '',
      text: '输入您的目的地',
      speed: 0,
      battery: 0,
      user_info: {},
      using_car_info: {},
      order_info: {},
      end_position: '',
      need_save_lat: 0,
      need_save_lng: 0,
      distance: 0,
      duration_time: 0,
      taxi_fare: 0,
      need_save_address: '',
      petrol__emissions: 0,
      electronic_emissions: 0,
      save_carbon_emissions: 0,
      tree__emissions: 0,
      gradientColor: {
        '0%': 'red',
        '100%': 'blue',
      },
    })
  },

  overUseCar(e) {
    this.data.using_car_info.battery = this.data.battery;
    if (this.data.need_save_address === '') {} else {
      this.data.using_car_info.address = this.data.need_save_address
    }
    if (this.data.need_save_lat === 0 || this.data.need_save_lng === 0) {} else {
      this.data.using_car_info.lat = this.data.need_save_lat;
      this.data.using_car_info.lng = this.data.need_save_lng;
    }
    if (this.data.distance === 0) {
      this.data.order_info.amount = this.data.using_car_info.price
    } else {
      this.data.using_car_info.distance = this.data.using_car_info.distance + this.data.distance / 1000;
      this.data.order_info.amount = this.data.using_car_info.distance * this.data.using_car_info.price
    }
    if (this.data.save_carbon_emissions === 0) {
      console.log(typeof this.data.save_carbon_emissions)
    } else {
      console.log(typeof this.data.using_car_info.saveCarbonEmissions)
      console.log(typeof this.data.save_carbon_emissions)
      this.data.using_car_info.saveCarbonEmissions = this.data.using_car_info.saveCarbonEmissions + parseFloat(this.data.save_carbon_emissions);
    }
    var that = this;
    wx.request({
      url: 'http://localhost:80/car/overUse',
      method: 'POST',
      data: that.data.using_car_info,
      success(res) {
        if (res.data.code === 1) {
          wx.request({
            url: 'http://localhost:80/order/overUse',
            method: 'POST',
            data: that.data.order_info,
            success(res) {
              if (res.data.code === 1) {
                that.setData({
                  using_car_info: {},
                })
                app.globalData.batteryStatus.battery = null
                //页面跳转前，先进行数据的清空重置
                that.clearData();
                wx.switchTab({
                  url: '../../pages/index/index',
                })
              }
            }
          })
        }
      }
    })
  },

  initLocation: function () {
    // 获取当前位置
    wx.getLocation({
      //是否开启高精度定位
      isHighAccuracy: true,
      type: 'gcj02',
      //高精度定位超时时间(ms)
      highAccuracyExpireTime: 6000,
      success: (res) => {
        const latitude = res.latitude;
        const longitude = res.longitude;
        const speed = 0;
        if (res.speed >= 0) {
          speed = res.speed;
        }
        this.setData({
          latitude: latitude,
          longitude: longitude,
          speed: speed
        });
        var that = this;
        qqmapsdk.reverseGeocoder({
          location: "" + that.data.latitude + "," + that.data.longitude,
          success(res) {
            console.log("当前位置解析成功");
            console.log(res.result);
            that.setData({
              now_address: res.result.address,
              now_address_name: res.result.formatted_addresses.recommend
            })
          }
        })
        this.startLocationUpdate();
      },
      fail: (err) => {
        console.log('获取位置失败', err);
      }
    });
  },
  startLocationUpdate: function () {
    // 开启实时位置监听
    wx.startLocationUpdate({
      success: (res) => {
        console.log('开启实时位置监听成功', res);
      },
      fail: (err) => {
        console.log('开启实时位置监听失败', err);
      }
    });

    // 监听位置变化事件
    wx.onLocationChange((res) => {
      console.log('位置发生变化', res);
      const that = this;
      const latitude = res.latitude;
      const longitude = res.longitude;
      const speed = 0;
      if (res.speed >= 0) {
        speed = res.speed;
      }
      this.setData({
        latitude: latitude,
        longitude: longitude,
        speed: speed
      });

      qqmapsdk.reverseGeocoder({
        location: "" + that.data.latitude + "," + that.data.longitude,
        success(res) {
          console.log(res.result);
          that.setData({
            now_address: res.result.address,
            now_address_name: res.result.formatted_addresses.recommend
          })
        }
      })

      wx.createSelectorQuery().select('#speedometer').boundingClientRect(rect => {
        const canvasWidth = rect.width;
        const canvasHeight = rect.height;

        that.drawSpeedometer(that.data.speed, canvasWidth, canvasHeight);
      }).exec();
      if (that.data.speed > 80) {
        wx.vibrateLong({
          success: (res) => {
            wx.showModal({
              title: '速度提醒',
              content: '请注意,当前车速达到80km/h,如果是非高速路段，安全起见请降低车速！',
              showCancel: false, // 不显示取消按钮
              confirmText: '确定',
              confirmColor: '#3CC51F',
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定');
                }
              },
            });
          },
        })
      }
    });
  },

  stopLocationUpdate: function () {
    // 停止实时位置监听
    wx.stopLocationUpdate();
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {



  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    qqmapsdk = new QQMapWX({
      key: 'X3SBZ-WSLW5-32QIB-I5FCH-R6N5J-6CFXI' // 必填
    });

    var userinfo1 = wx.getStorageSync('user_info');
    var that = this;
    this.setData({
      user_info: userinfo1
    })
    wx.request({
      url: 'http://localhost:80/order/queryUsingCar?userName=' + userinfo1.userName,
      method: 'GET',
      success(res) {
        console.log(res.data);
        that.setData({
          order_info: res.data.data
        })
        if (that.data.order_info != null) {
          wx.request({
            url: 'http://localhost:80/car/queryUsingCar?car_name=' + that.data.order_info.carName,
            method: 'GET',
            success(res) {
              that.setData({
                using_car_info: res.data.data,
                start: res.data.data.lat + "," + res.data.data.lng
              })
              /*
              wx.request({
                url: 'https://apis.map.qq.com/ws/coord/v1/translate?locations='+that.data.start+"&type=3"+"&key=X3SBZ-WSLW5-32QIB-I5FCH-R6N5J-6CFXI",
                method:'GET',
                success(res){
                  console.log(res.data.locations[0]);
                  that.setData({
                    start:res.data.locations[0].lng+","+res.data.locations[0].lat
                  })
                }
              })*/

              // 从数据库中获取电量值
              let batteryValueFromDatabase = that.data.using_car_info.battery; // 这里使用一个示例值，你需要从数据库中获取实际的电量值

              if (app.globalData.batteryStatus.battery === null) {
                app.globalData.batteryStatus.battery = batteryValueFromDatabase;
                that.setData({
                  battery: batteryValueFromDatabase
                })
              }

              // 设置定时器，每秒更新一次电量值
              if (app.globalData.batteryStatus.battery > 0) {
                app.globalData.batteryStatus.timer = setInterval(() => {
                  app.globalData.batteryStatus.battery -= 1;

                  // 如果电量值减少到 0，清除定时器
                  if (app.globalData.batteryStatus.battery <= 0) {
                    clearInterval(app.globalData.batteryStatus.timer);
                  }

                  if (app.globalData.batteryStatus.battery === 20) {
                    wx.vibrateLong({
                      success: (res) => {
                        wx.showModal({
                          title: '电量低警告',
                          content: '请注意，电量低于20%',
                          showCancel: false, // 不显示取消按钮
                          confirmText: '确定',
                          confirmColor: '#3CC51F',
                          success: function (res) {
                            if (res.confirm) {
                              console.log('用户点击确定');
                            }
                          },
                        });
                      },
                    })
                  }

                  // 将全局变量中的电量值同步到当前页面
                  that.setData({
                    battery: app.globalData.batteryStatus.battery
                  });
                }, 20000);
              }
            }
          })
        }
      }
    })
    if (that.data.order_info != null) {
      console.log("执行位置初始化成功");
      this.initLocation();
      const that = this;
      wx.createSelectorQuery().select('#speedometer').boundingClientRect(rect => {
        const canvasWidth = rect.width;
        const canvasHeight = rect.height;

        that.drawSpeedometer(that.data.speed, canvasWidth, canvasHeight);
      }).exec();
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.stopLocationUpdate();
    // 清除定时器
    clearInterval(app.globalData.batteryStatus.timer);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})